<template>
  <div class="news_edit">
    <el-row class="edit_main">
      <div class="newsList">
        <h3 class="tit">图文列表</h3>
        <draggable ref="drag" v-model="news.articles" element="ul" class="list" :size="news.articles.length" :move="handleDrag">
          <li v-for="item,n in news.articles" :class="{newsItem: true, checked: n === curNews}" @click="handleSelectNews(n)">
            <img v-if="item.sourceId" :src="baseUrl + '/content/source/id/' + item.sourceId" alt="">
            <img v-else src="../../../assets/bg/pic_blank.gif" alt="">
            <div class="newsTit">{{item.title}}</div>
            <div class="newsDel"><i @click.stop.prevent="handleDelNews(n)" class="el-icon-delete"></i></div>
          </li>
          <li class="btn-add" @click="handleAddNews"><i class="el-icon-plus"></i></li>
        </draggable>
      </div>
      <div class="editorBox">
        <wechat-editor ref="editor"
          :title.sync="title"
          :author.sync="author" 
          :content="content"
          @contentChange="handleEditorChange"
        >
        </wechat-editor>
        <div class="newsInfo">
          <h4>原文链接</h4>
          <el-row><el-input v-model="url"></el-input></el-row>
          <h4>发布样式编辑</h4>
          <h5>封面</h5>
          <div>
            <el-button @click="step=0;visible2=true;">从图片库选择</el-button>
            <img v-if="checkedNews.sourceId" class="cover" :src="baseUrl + '/content/source/id/' + checkedNews.sourceId" alt="">
          </div>
          <h5>摘要</h5>
          <div>
            <el-input type="textarea" v-model="digest" placeholder="选填，如果不填写会默认抓取正文前54字"></el-input>
          </div>
        </div>
        <div class="editBottom">
          <el-row>
            <el-select v-model="attribute" placeholder="内容性质">
              <el-option v-for="item,n in attrs" :value="item.id" :label="item.name" :key="n.toString()"></el-option>
            </el-select>
            <el-checkbox v-model="groupType" :true-label="1" :false-label="0">上传到事业部内容库</el-checkbox>
            <el-checkbox v-if="showCommonType" v-model="commonType" :true-label="1" :false-label="0">上传到公共内容库</el-checkbox>
          </el-row>
          <el-row>
            <template v-if="news.save || id == 'new'" >
              <el-button type="primary" @click="id == 'new'?handleSaveAs():handleSave()" :loading="isSave">保存</el-button>
              <el-button type="primary" @click="id == 'new'?handleSaveAsSend():handleSaveSend()" :loading="isSave">保存并发送</el-button>
            </template>
            <el-button v-if="id != 'new'" type="primary" @click="handleSaveAs" :loading="isSave">另存为</el-button>
          </el-row>
        </div>
      </div>
      <dl class="multiMedia">
        <dt>多媒体</dt>
        <dd @click="visible1 = true">图片</dd>
        <dd @click="$alert('功能开发中...')">视频</dd>
        <dd @click="$alert('功能开发中...')">音频</dd>
        <dd @click="$alert('功能开发中...')">投票</dd>
      </dl>
    </el-row>
    <!-- 选择图片 -->
    <el-dialog ref="dialog" title="选择图片" :visible.sync="visible1" class="dialog_cover" @open="SELECT_SOURCE({})">
      <dialog-image></dialog-image>
      <div slot="footer">
        <el-button type="primary" @click="handleAddImg()" :loading="isSave">确定</el-button>
        <el-button @click="visible1=false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 选择音频 -->
<!--     <el-dialog ref="dialog3" title="选择图片" :visible.sync="visible3" class="dialog_cover">
      <dialog-audio></dialog-audio>
      <div slot="footer">
        <el-button type="primary" :loading="isSave" @click="handleAddAudio">确定</el-button>
        <el-button @click="visible3=false">取消</el-button>
      </div>
    </el-dialog> -->
    <!-- 选择封面 -->
    <el-dialog ref="dialog2" :title="step==0?'选择图片':'裁切图片'" :visible.sync="visible2" class="dialog_cover" @open="SELECT_SOURCE({})">
      <dialog-image v-if="step==0"></dialog-image>
      <img-clipper ref="clipper" v-if="step==1" :imgSrc="selected.url" :ratio="curNews == 0 ? 9/5 : 1"></img-clipper>
      <div slot="footer">
        <el-button v-if="step==0" type="primary" @click="step=1">下一步</el-button>
        <el-button v-if="step==1" type="primary" @click="step=0">上一步</el-button>
        <el-button v-if="step==1" type="primary" @click="handleSetCover" :loading="isSave">确定</el-button>
        <el-button @click="visible2=false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 发送设置 -->
    <dialog-send ref="dialogSend"></dialog-send>
  </div>
</template>
<script>
  import {mapState, mapActions, mapMutations} from 'vuex'
  import dialogImage from '@/components/common/content/dialogImage'
  import dialogAudio from '@/components/common/content/dialogAudio'
  import wechatEditor from '@/components/common/content/wechatEditor'
  import dialogSend from '@/components/common/content/wxSendDialog'
  import draggable from 'vuedraggable'
  import imgClipper from '@/components/common/clipper'
  import config from '@/config/env'
  export default {
    components: {wechatEditor, dialogImage, dialogAudio, dialogSend, imgClipper, draggable},
    data () {
      return {
        id: this.$route.params.id,
        curNews: 0,
        step: 0,
        showCommonType: true,
        visible1: false,
        visible2: false,
        visible3: false,
        isSave: false
      }
    },
    activated () {
      this.$bus.$emit('menuCollapse', true)
      this.initPage()
    },
    computed: {
      ...mapState({
        news: state => state.contentManage.wxNewsDetail,
        sourceInfo: state => state.sourceManage.sourceInfo,
        selected: state => state.sourceManage.selected,
        attrs: state => state.contentManage.contentType
      }),
      baseUrl () {
        return config.baseUrl
      },
      checkedNews () {
        return this.news.articles[this.curNews] || {}
      },
      content: {
        get () {
          return this.checkedNews.content
        }
      },
      title: {
        get () {
          return this.checkedNews.title
        },
        set (val) {
          this.checkedNews.title = val
          this.UPDATE_WX_NEWS(this.news)
        }
      },
      author: {
        get () {
          return this.checkedNews.author
        },
        set (val) {
          this.checkedNews.author = val
          this.UPDATE_WX_NEWS(this.news)
        }
      },
      digest: {
        get () {
          return this.checkedNews.digest
        },
        set (val) {
          this.checkedNews.digest = val
          this.UPDATE_WX_NEWS(this.news)
        }
      },
      attribute: {
        get () {
          return this.news.attributes
        },
        set (val) {
          this.UPDATE_WX_NEWS({attributes: val})
        }
      },
      url: {
        get () {
          return this.checkedNews.contentSourceUrl
        },
        set (val) {
          this.checkedNews.contentSourceUrl = val
          this.UPDATE_WX_NEWS(this.news)
        }
      },
      groupType: {
        get () {
          return this.news.groupType
        },
        set (val) {
          this.UPDATE_WX_NEWS({groupType: val})
        }
      },
      commonType: {
        get () {
          return this.news.commonType
        },
        set (val) {
          this.UPDATE_WX_NEWS({commonType: val})
        }
      }
    },
    methods: {
      ...mapMutations(['UPDATE_WX_NEWS', 'INIT_WX_NEWS', 'SELECT_SOURCE', 'UPDATE_WX_SEND_INFO']),
      ...mapActions(['getWxNewsDetail', 'getWxSourceInfo2', 'setWxNews', 'uploadImage', 'getContentTypes']),
      // 页面初始化
      async initPage () {
        this.id = this.$route.params.id
        this.showCommonType = true
        await this.getContentTypes()
        if (this.id !== 'new') {
          await this.getWxNewsDetail(this.id)
          this.showCommonType = !this.news.commonType
          this.$refs.editor.setContent(this.checkedNews.content)
        } else {
          this.INIT_WX_NEWS()
          this.attribute = this.attrs[0].id
        }
      },
      // 选择图文
      handleSelectNews (index) {
        this.curNews = index
        this.$refs.editor.setContent(this.checkedNews.content)
      },
      // 添加图片
      async handleAddImg () {
        this.visible1 = false
        await this.getWxSourceInfo2(this.selected.id)
        const html = `<img src="${this.sourceInfo.wxUrl}" style="max-width:100%" />`
        this.$refs.editor.execCommand('inserthtml', html)
      },
      // 添加音频
      // async handleAddAudio () {
      //   this.visible3 = false
      //   const yinpin = `<iframe frameborder="0" class="res_iframe js_editor_audio audio_iframe" src="https://mp.weixin.qq.com/cgi-bin/readtemplate?t=tmpl/audio_tmpl&amp;name=888&amp;play_length=00:03" isaac2="1" low_size="4.07" source_size="4.1" high_size="28.82" name="888" play_length="3000" voice_encode_fileid="$VOICE_MEDIAID_$"></iframe>`
      //   this.$refs.editor.execCommand('inserthtml', yinpin)
      // },
      // 编辑器内容改变
      handleEditorChange (content) {
        this.checkedNews.content = content
        this.UPDATE_WX_NEWS(this.news)
      },
      // 设置封面
      async handleSetCover () {
        const file = this.$refs.clipper.clip()
        const data = new FormData()
        data.append('file', file)
        data.append('name', '微信图文封面' + Date.now())
        data.append('contentType', 1)
        data.append('weixinThumb', 1)
        this.isSave = true
        let res = await this.uploadImage(data)
        this.isSave = false
        this.visible2 = false
        this.checkedNews.sourceId = res.data.data.id
        this.UPDATE_WX_NEWS(this.news)
      },
      // 添加图文
      handleAddNews () {
        const index = this.news.articles.length
        this.news.articles.push({title: '', author: '', content: '', showCoverPic: '0', index})
        this.UPDATE_WX_NEWS({
          articles: this.news.articles
        })
      },
      // 移动图文
      handleDrag () {
        // console.log(this.news.articles)
      },
      // 删除图文
      handleDelNews (index) {
        this.news.articles.splice(index, 1)
        this.curNews === index && index && this.handleSelectNews(index - 1)
        !index && this.$refs.editor.setContent('')
      },
      // 保存
      async save () {
        if (!this.submitCheck()) {
          return false
        }
        const id = +this.id
        // 同步index
        this.news.articles.map((item, n) => { item.index = n })
        const promise = this.setWxNews({...this.news, id})
        const res = await promise
        this.isSave = false
        if (res.data.code === 1) {
          this.$message.success('保存成功')
        } else {
          this.$message({
            type: 'warning',
            message: res.data.msgZ
          })
        }
        return promise
      },
      async handleSave () {
        const res = await this.save()
        if (res.data.code === 1) {
          this.$router.go(-1)
        }
      },
      // 保存并发送
      async handleSaveSend () {
        const res = await this.save()
        if (res.data.code === 1) {
          this.UPDATE_WX_SEND_INFO({id: this.id})
          this.$refs.dialogSend.visible = true
        }
      },
      // 另存为
      async saveAs () {
        if (!this.submitCheck()) {
          return false
        }
        // 同步index
        this.news.articles.map((item, n) => { item.index = n })
        this.isSave = true
        const promise = this.setWxNews({...this.news, commonType: this.showCommonType ? this.news.commonType : 0})
        const res = await promise
        this.isSave = false
        if (res.data.code === 1) {
          this.$message.success(res.data.msgZ)
        } else {
          this.$message({
            type: 'warning',
            message: res.data.msgZ
          })
        }
        return promise
      },
      async handleSaveAs () {
        const res = await this.saveAs()
        if (res.data.code === 1) {
          this.$router.go(-1)
        }
      },
      // 另存为并发送
      async handleSaveAsSend () {
        const res = await this.saveAs()
        if (res.data.code === 1) {
          this.UPDATE_WX_SEND_INFO({id: res.data.data.logicId})
          this.$refs.dialogSend.visible = true
        }
      },
      // 保存校验
      submitCheck () {
        if (!this.news.attributes) {
          this.$message.error('请选择内容性质')
          return false
        }
        for (let key in this.news.articles) {
          const item = this.news.articles[key]
          if (!item.title) {
            this.$message.error(`请输入图文${1 + (+key)}的标题`)
            return false
          }
          if (!item.author) {
            this.$message.error(`请输入图文${1 + (+key)}的作者`)
            return false
          }
          if (!item.content) {
            this.$message.error(`请输入图文${1 + (+key)}的内容`)
            return false
          }
          if (!item.contentSourceUrl) {
            this.$message.error(`请输入图文${1 + (+key)}的原文链接`)
            return false
          }
          if (!/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-.,@?^=%&:/~+#]*[\w\-@?^=%&/~+#])?/.test(item.contentSourceUrl)) {
            this.$message.error(`图文${1 + (+key)}的原文链接格式不对`)
            return false
          }
          if (!item.sourceId) {
            this.$message.error(`请选择图文${1 + (+key)}的封面`)
            return false
          }
        }
        return true
      }
    }
  }
</script>
<style lang="scss">
  .news_edit {
    &{min-width:1000px;overflow:auto}
    .el-row{margin-bottom:15px;}
    .edit_main{min-width:1300px;}
    .newsList{
      &{float:left;padding:0 20px 10px 20px;width:210px;}
      .tit{margin-bottom:20px;font-size:14px;font-weight:500;}
      .newsItem{
        &{position:relative;margin-top:-1px;padding:10px;border:1px solid #e7e7eb;cursor:pointer;}
        &.checked{border:1px solid #43b548}
        &.checked~.newsItem{margin-top:0;border-top:0;}
        img{display:block;width:188px;height:120px;}
        .newsTit{position:absolute;left:10px;bottom:10px;width:188px;height:28px;background:rgba(0,0,0,.6);color:#fff;font-size:14px;text-align:center;line-height:28px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
        .newsDel{position: absolute; top: 10px; right: 10px; display: none;text-align: right;background: rgba(255,255,255, .5); height: 24px;width: 188px; line-height: 24px;}
        .el-icon-delete{font-size: 20px;}
        &:hover .newsDel{
          display: block;
        }
      }
      .btn-add{margin-top:-1px;width:100%;height:90px;line-height:90px;border:1px solid #e7e7eb;text-align:center;box-sizing:border-box;font-size:20px;cursor:pointer;}
    }
    .multiMedia{
      &{float:left;margin-left:20px;}
      dt{margin-bottom:20px;font-size:14px}
      dd{margin-bottom:-1px;padding-left:20px;width:168px;height:50px;line-height:50px;border:1px solid #e7e7eb;box-sizing:border-box;font-size:14px;cursor:pointer}
    }
    .editorBox{
      &{float:left;}
      .newsInfo{
        &{margin-top:-1px;padding:20px;border:1px solid #d4d4d4}
        h4{margin-bottom:10px;font-size:14px;}
        h5{margin-top:10px;line-height:28px;}
      }
      .cover{display:block;margin-top:10px;width:120px;height:120px;}
      .editBottom{margin-top:20px;text-align:center;}
    }
    .dialog_cover{
      .img_clipper{margin:0 auto;}
    }
  }
</style>
